﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Workflow.Application.DTOs.Input;
using Workflow.Application.IService;
using Workflow.Application.Service;
using Workflow.Domain.Enums;
using Workflow.Domain.Models;
using Workflow.Infrastructure.IRepository;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using Yitter.IdGenerator;

namespace Workflow.Application.Step
{
    public class AuditStep_back : StepBodyAsync
    {
        public long AuditUserId {  get; set; }
        private readonly IBaseRepository<WorkflowInstanceModel> instanceBase;
        private readonly IBaseRepository<AuditModel> auditBase;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="instanceBase"></param>
        /// <param name="auditBase"></param>
        public AuditStep_back(IBaseRepository<WorkflowInstanceModel> instanceBase, IBaseRepository<AuditModel> auditBase)
        {
            this.instanceBase = instanceBase;
            this.auditBase = auditBase;
        }

        public override async Task<ExecutionResult> RunAsync(IStepExecutionContext context)
        {
            if (!context.ExecutionPointer.EventPublished)
            {
                //修改流程实例列表
                var instance = await instanceBase.GetValue(x=>x.WorkflowInstanceId==context.Workflow.Id);
                instance.CurrentStepId= context.Step.ExternalId;
                instance.CurrentStepName= context.Step.Name;
                instance.StatuEnum= WorkflowInstanceStatuEnum.Processing;
                instance.CurrentAuditUserIds = AuditUserId.ToString();
                //instance.CurrentAuditUsers = AuditUserName.ToString();
                //添加审批信息
                AuditModel audit = new AuditModel()
                {
                    Id = YitIdHelper.NextId(),
                    AuditUserId= AuditUserId,
                    //AuditUserName= AuditUserName,
                    WorkflowId = context.Workflow.Id,
                    StepId = context.Step.ExternalId,
                    StepName = context.Step.Name,
                    StatuEnum= WorkFlowAuditStatuEnum.UnAudited,
                };
                //分布式事务
                using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        await instanceBase.UpdateRange(instance);
                        await auditBase.AddRange(audit);
                        tran.Complete();
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
                return ExecutionResult.WaitForEvent(audit.Id.ToString(), context.Workflow.Id, DateTime.Now);
            }
            // 获取审批意见
            var eventData = context.ExecutionPointer.EventData as AuditInput;
            //当审批结果是拒绝时
            if (eventData.OperateTypeEnum == WorkFlowAuditStatuEnum.UnApprove)
            {
                var instance = await instanceBase.GetValue(x=>x.WorkflowInstanceId== context.Workflow.Id);
                instance.StatuEnum = WorkflowInstanceStatuEnum.Reject;
                instance.CurrentStepId = nameof(EndStep);
                instance.CurrentStepName = nameof(EndStep);
                instance.CurrentAuditUsers = "";
                instance.UpdatedTime = DateTime.Now;
                await instanceBase.UpdateRange(instance);
                context.Workflow.Status = WorkflowStatus.Complete;
                context.Workflow.CompleteTime = DateTime.Now;
            }
            // 流转到下一个节点
            return ExecutionResult.Next();
        }
    }
}
